from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from blog.models import Article
from .forms import CommentForm
from .models import Comment


# Create your views here.
@login_required
def CommentView(request, article_id):
    article = Article.objects.get(aid=article_id)
    if request.method == "POST":
        form = CommentForm(request.POST)
        print(form)
        if form.is_valid():
            content = form.cleaned_data['comment']
            newComment = Comment(
                content=content,
                article=article,
                author=request.user
            )
            # if form.cleaned_data['parent_comment_id']:
            #     parentComment = Comment.objects.get(
            #         pk=form.cleaned_data['parent_comment_id']
            #     )
            #     newComment.parentComment = parentComment
            newComment.save()

            # 之后或许可以通过 django.shortcuts.redirect 实现
            # 需要完成模型中的子方法 get_absolute_url()
            path = "/blog/article/" + str(article.author.username)\
                + '/' + str(article.aid)
            return HttpResponseRedirect(path)
        else:
            return HttpResponse("表单内容有误，请重新提交！！！")
    else:
        return HttpResponse("评论恐怕仅支持POST请求")
